import React, { Component } from 'react';
import * as echarts from "echarts";


export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            formula: [],
            strategy: []
        }
    }

    add(value) {
        this.state.formula.push(value);
        this.setState(()=>{
            return {
                formula: this.state.formula
            }
        });
    }

    edit(value) {
        this.remove_strategy(value);
        this.setState(()=>{return {formula: value}});
    }

    remove(value){
        for (let index in this.state.formula){
            if (value.name === this.state.formula[index].name){
                this.state.formula.splice(index, 1);
            }
        }
        this.setState(()=>{return {formula: this.state.formula}});
    }

    add_strategy() {
        if (this.state.formula.length > 0){
            this.state.strategy.push(this.state.formula);
            this.state.formula = [];
            this.setState(()=>{return {
                strategy: this.state.strategy,
                formula: this.state.formula
            }});
        }
    }

    remove_strategy(value) {
        for (let index in this.state.strategy){
            if (JSON.stringify(value) === JSON.stringify(this.state.strategy[index])){
                this.state.strategy.splice(index, 1);
            }
        }
        this.setState(()=>{return {strategy: this.state.strategy}});
    }

    render() {
        let formulabtns = this.state.formula;
        let strategyRows = this.state.strategy;
        return (
            <div>
                <ul className="nav nav-tabs" role="tablist">
                    <li role="presentation" className="active">
                        <a href="#home" aria-controls="home" role="tab" data-toggle="tab">策略</a>
                    </li>
                    <li role="presentation">
                        <a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">模拟</a>
                    </li>
                </ul>
                <div className="tab-content col-lg-12">
                    <div role="tabpanel" className="tab-pane active" id="home">
                        <StrategyForm formula={formulabtns} strategy={strategyRows}
                                      add={this.add.bind(this)}
                                      edit={this.edit.bind(this)}
                                      remove={this.remove.bind(this)}
                                      add_strategy={this.add_strategy.bind(this)}
                                      remove_strategy={this.remove_strategy.bind(this)}
                        />
                    </div>
                    <div role="tabpanel" className="tab-pane" id="profile">
                        <SimulationForm strategy={this.state.strategy}/>
                    </div>
                </div>
            </div>
        );
    }
}


class SimulationForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            args: {
                money: 100000,
                date: {field: 'history', data: {st:'2018-01-01', ed: '2018-07-01'}},
                code: {field: 'code', data: '600361'},
                buy: {st: 0, ed: 100},
                sell: {st: 0, ed: 100},
                match: {st: 0, ed: 100}
            },
            rows: [], //name, data
        }
    }
    edit_args(field, value, def) {
        switch (field) {
            case 'money':
                this.state.args.money = value;
                break;

            case 'date':
            case 'code':
                let args = value.split('@');
                if (this.state.args[field].field !== args[0]){
                    this.state.args[field].field = args[0];
                    if (args[1].indexOf('|') !== -1)
                        this.state.args[field].data = {st: def.st, ed: def.ed};
                    else
                        this.state.args[field].data = def;
                }

                if (args[1].indexOf('|') !== -1){
                    let range = args[1].split('|');
                    if (range[0] !== '-')
                        this.state.args[field].data.st = range[0];
                    if (range[1] !== '-')
                        this.state.args[field].data.ed = range[1];
                }else{
                    this.state.args[field].data = args[1];
                }
                break;

            case 'buy':
            case 'sell':
            case 'match':
                let range = value.split('|');
                if (range[0] !== '-' && range[0] !== '')
                    this.state.args[field].st = parseInt(range[0]);
                if (range[1] !== '-' && range[1] !== '')
                    this.state.args[field].ed = parseInt(range[1]);
                break;
        }
        this.setState(()=>{
            return {
                args: this.state.args
            }
        });
        console.log(this.state.args);
    }

    ToOldArgs(){
        let date = this.state.args.date.data;
        if (this.state.args.date.field === 'history'){
            date = [this.state.args.date.data.st, this.state.args.date.data.ed].join(',')
        }

        return {
            mode_code: {
                key: this.state.args.code.field,
                value:this.state.args.code.data
            },
            mode_time: {
                key: this.state.args.date.field,
                value: date
            },
            buy_rate: [this.state.args.buy.st, this.state.args.buy.ed].join(','),
            sell_rate: [this.state.args.sell.st, this.state.args.sell.ed].join(','),
            up: this.state.args.match.ed,
            down: this.state.args.match.st,
            money: this.state.args.money,
            strategy: $("#strategy_name").val(),
            formulas: JSON.stringify(this.props.strategy)
        };
    }

    TimeoutGetSimulate(){
        $.post(`/config/get_simulate/`, this.ToOldArgs(), (data)=> {
            if (data.ret === true){
                this.state.rows = [{'name': this.state.args.code.data, 'report':data.data}];
                this.setState(()=>{return {rows: this.state.rows}});
            }else{
                setTimeout(()=>this.TimeoutGetSimulate(), 1000);
            }
        });
    }

    TimeoutGetMatch(count){
        $.post(`/config/get_match/`, args, (data)=> {
            for (let row of data){
                this.state.rows.push({'name': row.code, 'report': row.data});
                count -= 1
            }
            this.setState(()=>{return {rows: this.state.rows}});
            if (count > 0){
                setTimeout(()=>this.TimeoutGetMatch(count-1), 1000);
            }
        });
    }

    Simulation(){
        let args = this.ToOldArgs();
        $.post(`/config/simulate/`, args);
        this.setState(()=>{return {rows: []}});
        this.TimeoutGetSimulate();
    }

    Match(){
        let args = this.ToOldArgs();
        $.post(`/config/match/`, args);
        this.setState(()=>{return {rows: []}});
        let count = parseInt(this.state.args.code.data);
        if (count > 10)
            count = 10;
        this.TimeoutGetMatch(count);
    }

    render(){
        let chartShow = <div className='row' />;
        if (this.state.rows.length > 0){
            chartShow = <div className='row'><ReportShow data={this.state.rows} /></div>;
        }
        return (
            <div>
                <div className="row">
                    <div className='col-lg-3'>
                        <div className="btn-group">
                            <button type="button" className="btn btn-default" onClick={this.Simulation.bind(this)}>Simulation</button>
                            <button type="button" className="btn btn-default" onClick={this.Match.bind(this)}>Match</button>
                            <button type="button" className="btn btn-default" onClick={()=>{$("input").val("");}}>Clear</button>
                        </div>
                    </div>
                    <div className='col-lg-9'>
                        <SimulationInput edit={this.edit_args.bind(this)} data={this.state.args}/>
                    </div>
                </div>
                {chartShow}
            </div>
        );
    }
}

class ReportShow extends Component{
    constructor(props) {
        super(props);
    }
    ChangeSelect(event){
        console.log("changeSelect", event.target.text, this.props.data);
    }
    render() {
        let btns = this.props.data.map((item)=>{return <li><a href="#" onClick={this.ChangeSelect.bind(this)}>{item.name}</a></li>});
        let select = this.props.data[0];
        let report = select.report;
        let total = report.total,
            date = report.date,
            money = report.money,
            pass = report.pass,
            flag = report.flag,
            quota = report.quota;

        let price = {};
        for (let code in report.market){
            price[code] = [];
            for (let data of report.market[code]){
                price[code].push(parseFloat(data.split(',')[1]));
            }
        }
        console.log(price, pass);
        return (
            <div className='col-lg-12'>
                <div className="row">
                    <div className="col-lg-12">
                        <ReportTotal data={total} name={select.name} list={btns}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-lg-12">
                        <ReportChart title="账户市值趋势"  id='money' xAxis={date} series={money}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-lg-6">
                        <ReportChartMultiLine title="交易信号和价格" id='flag' xAxis={date} series={price} flag={flag}/>
                    </div>
                    <div className="col-lg-6">
                        <ReportChartMultiLine title="策略通过趋势" id='pass' xAxis={date} series={pass}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-lg-12">
                        <ReportMultiChartMultiLine title="指标变化趋势" id='quota' xAxis={date} data={quota}/>
                    </div>
                </div>
            </div>
        );
    }
}
class ReportTotal extends Component{
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="row" id="table" style={{disply: this.props.display}}>
                <div className="panel panel-default">
                    <table className="table">
                        <tr>
                            <td>当前显示股票</td>
                            <td><div className="input-group">
                                <button type="button" className="btn btn-xs btn-primary dropdown-toggle"
                                        data-toggle="dropdown"
                                        aria-haspopup="true" aria-expanded="false">
                                    {this.props.name} <span className="caret" />
                                </button>
                                <ul className="dropdown-menu">{this.props.list}</ul>
                            </div></td>
                            <td/>
                            <td/>
                        </tr>
                        <tr>
                            <td>平均盈利金额</td>
                            <td>{this.props.data.avg_profit_money}</td>
                            <td>平均损失金额</td>
                            <td>{this.props.data.avg_loss_money}</td>
                        </tr>
                        <tr>
                            <td>买入次数</td>
                            <td>{this.props.data.buy_count}</td>
                            <td>总共买入持仓</td>
                            <td>{this.props.data.buy_position}</td>
                        </tr>
                        <tr>
                            <td>卖出次数</td>
                            <td>{this.props.data.sell_count}</td>
                            <td>总共卖出持仓</td>
                            <td>{this.props.data.sell_position}</td>
                        </tr>
                        <tr>
                            <td>操作获胜概率</td>
                            <td>{this.props.data.profit}</td>
                            <td>年化收益率</td>
                            <td>暂不显示</td>
                        </tr>
                    </table>
                </div>
            </div>
        );
    }
}
class ReportChartMultiLine extends Component{
    constructor(props) {
        super(props);
    }
    componentDidMount(){
        let myChart = echarts.init(document.getElementById(this.props.id));
        let legend = [], series = [];
        for (let item in this.props.series){
            let point = [];
            if (this.props.flag !== undefined){
                for (let i in this.props.flag[item]){
                    switch (this.props.flag[item][i]){
                        case '+':
                            point.push({ symbolRotate:180, symbol:'arrow', value:'+', xAxis: this.props.xAxis[i], yAxis: this.props.series[item][i], symbolSize: [10, 15], itemStyle: {color: '#6091c1'} });
                            break;
                        case '-':
                            point.push({ symbolRotate:0, symbol:'arrow', value:'-', xAxis: this.props.xAxis[i], yAxis: this.props.series[item][i], symbolSize: [10, 15], itemStyle: {color: 'green'} });
                            break
                    }
                }
            }
            legend.push(item);
            series.push({
                data: this.props.series[item],
                type: 'line',
                smooth: true,
                name: item,
                markPoint: {
                    data: point
                }
            });
        }
        myChart.setOption({
            title: {
                left: 'left',
                text: this.props.title,
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#283b56'
                    }
                }
            },
            legend: {
                left: 'right',
                data: legend
            },
            xAxis: {
                type: 'category',
                data: this.props.xAxis
            },
            yAxis: [
                {
                    type: 'value',
                    scale: true,
                    precision: 2,
                    splitNumber: 9,
                    boundaryGap: [0.01, 0.01],
                    splitArea: { show: true }
                }
            ],
            series: series
        });
    }
    render() {
        return (
            <div id={this.props.id} style={{height: '300px'}}/>
        );
    }
}
class ReportChart extends Component{
    constructor(props) {
        super(props);
    }
    componentDidMount(){
        let myChart = echarts.init(document.getElementById(this.props.id));
        myChart.setOption({
            title: {
                left: 'center',
                text: this.props.title,
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#283b56'
                    }
                }
            },
            xAxis: {
                type: 'category',
                data: this.props.xAxis
            },
            yAxis: [
                {
                    type: 'value',
                    scale: true,
                    precision: 2,
                    splitNumber: 9,
                    boundaryGap: [0.01, 0.01],
                    splitArea: { show: true }
                }
            ],
            series: [
                {
                    data: this.props.series,
                    type: 'line',
                    smooth: true
                },
            ]
        });
    }
    render() {
        return (
            <div id={this.props.id} style={{height: '300px'}}/>
        );
    }
}
class ReportMultiChartMultiLine extends Component{
    constructor(props) {
        super(props);
        this.state = {
            code: ''
        }
    }
    componentDidMount(){
        this.SetOption(this.state.code);
    }
    SetOption(code){
        let myChart = echarts.init(document.getElementById(this.props.id));
        let series = [];
        for (let index in this.props.data[code].rows){
            series.push({
                data: this.props.data[code].rows[index],
                type: 'line',
                smooth: true,
                name: this.props.data[code].label[index]
            });
        }
        myChart.setOption({
            title: {
                left: 'left',
                text: this.props.title,
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#283b56'
                    }
                }
            },
            legend: {
                left: 'right',
                data: this.props.data[code].label
            },
            xAxis: {
                type: 'category',
                data: this.props.xAxis
            },
            yAxis: [
                {
                    type: 'value',
                    scale: true,
                    precision: 2,
                    splitNumber: 9,
                    boundaryGap: [0.01, 0.01],
                    splitArea: { show: true }
                }
            ],
            series: series
        });
    }
    ChangeData(event){
        this.SetOption(event.target.text);
    }
    render() {
        let btns = [];
        for (let i in this.props.data){
            btns.push(i);
        }
        this.state.code = btns[0];
        return (
            <div>
                <div className='row'>
                    <div className="input-group">
                        <div className="input-group-btn">
                            <button type="button" className="btn btn-default dropdown-toggle"
                                    data-toggle="dropdown" id="quota_select"
                                    aria-haspopup="true" aria-expanded="false">
                                请选择股票的指标趋势<span className="caret" />
                            </button>
                            <ul className="dropdown-menu">
                                {btns.map(name => {return <li><a onClick={this.ChangeData.bind(this)}>{name}</a></li>})}
                            </ul>
                        </div>
                    </div>
                </div>
                <div className='row'>
                    <div id={this.props.id} style={{height: '300px'}}/>
                </div>
            </div>
        );
    }
}

class SimulationInput extends Component{
   constructor(props) {
       super(props);
   }

   MoneyChagne(event){
       this.props.edit('money', event.target.value);
   }

   render() {
       return (
           <div>
               <div className="row">
                   <div className="col-lg-4">
                       <SIButtonText field='date' list={[
                           {id: 0, name: '指定区间' , mode: 'range', field: 'history', def: {st: '2018-01-01', ed: '2018-07-01'}},
                           {id: 1, name: '随机区间' , mode: 'single', field: 'random', def: '100'},
                           {id: 2, name: '正太模拟' , mode: 'single', field: 'sd', def: '60'},
                       ]} edit={this.props.edit}/>
                   </div>
                   <div className="col-lg-4">
                       <div className="input-group">
                           <span className="input-group-addon" id="SF_basic-addon3">金额</span>
                           <input type="text" className="form-control" aria-describedby="SF_basic-addon3" onChange={this.MoneyChagne.bind(this)} placeholder={this.props.data.money} />
                       </div>
                   </div>
                   <div className="col-lg-4">
                       <SIButtonText field='code' list={[
                           {id: 0, name: '代码' , mode: 'single', field: 'code', def: '600361'},
                           {id: 1, name: '行业' , mode: 'single', field: 'industry', def: 'IT'},
                           {id: 2, name: '随机' , mode: 'single', field: 'random', def: '10'},
                       ]} edit={this.props.edit}/>
                   </div>
               </div>
               <div className='row'>
                   <div className='col-lg-4'>
                       <SITextRange field='buy' edit={this.props.edit} name={"买入范围"} def={{st:0, ed: 100}}/>
                   </div>
                   <div className='col-lg-4'>
                       <SITextRange field='sell' edit={this.props.edit} name={"卖出范围"} def={{st:0, ed: 100}}/>
                   </div>
                   <div className='col-lg-4'>
                       <SITextRange field='match' edit={this.props.edit} name={"匹配范围"} def={{st:0, ed: 100}}/>
                   </div>
               </div>
           </div>
       );
   }
}
class SITextRange extends Component {
    constructor(props) {
        super(props);
    }

    stChange(event){
        this.props.edit(this.props.field, `${event.target.value}|-`, this.props.def);
    }

    edChange(event){
        this.props.edit(this.props.field, `-|${event.target.value}`, this.props.def);
    }

    render() {
        return (
            <div className="input-group">
                <span className='input-group-btn' style={{fontSize: '16'}}>{this.props.name}</span>
                <input type="text" className="form-control" style={{width: '49%', marginLeft: '1%'}} placeholder='0' onChange={this.stChange.bind(this)}/>
                <input type="text" className="form-control" style={{width: '50%'}} placeholder='100' onChange={this.edChange.bind(this)}/>
            </div>
        );
    }
}
class SIButtonText extends Component {
    constructor(props) {
        super(props);
        this.state = {
            select: 0
        }
    }

    ChangeSelect(value) {
        let index = value.target.tabIndex;
        let select = this.props.list[index];
        if (select.mode === 'range')
            this.props.edit(this.props.field, `${select.field}@${[select.def.st, select.def.ed].join('|')}`, select.def);
        else
            this.props.edit(this.props.field, `${select.field}@${select.def}`, select.def);
        this.setState(()=>{
            return {
                select: index
            };
        });
    }

    Change(event){
        let select = this.props.list[this.state.select];
        if (select.mode === 'range'){
            if (event.target.className.indexOf('st') !== -1){
                this.props.edit(this.props.field, `${select.field}@${event.target.value}|-`, select.def);
            }else{
                this.props.edit(this.props.field, `${select.field}@-|${event.target.value}`, select.def);
            }
        }else{
            this.props.edit(this.props.field, `${select.field}@${event.target.value}`, select.def);
        }
    }


    render() {
        let btns = this.props.list.map((item)=>{
            return <li><a href="#" onClick={this.ChangeSelect.bind(this)} tabIndex={item.id}>{item.name}</a></li>
        });
        let select = this.props.list[this.state.select];
        let input = (<input type="text" className="form-control single" placeholder={select.def} style={{width: '100%'}} onChange={this.Change.bind(this)}/>);
        if (select.mode === 'range'){
            input = (
                <div className="input-group">
                    <input type="text" className="form-control st" placeholder={select.def.st} style={{width: '50%'}} onChange={this.Change.bind(this)}/>
                    <input type="text" className="form-control ed" placeholder={select.def.ed} style={{width: '50%'}} onChange={this.Change.bind(this)}/>
                </div>
            );
        }

        return (
            <div className="input-group">
                <div className="input-group-btn">
                    <button type="button" className="btn btn-default dropdown-toggle"
                            data-toggle="dropdown"
                            aria-haspopup="true" aria-expanded="false">
                        {select.name} <span className="caret" />
                    </button>
                    <ul className="dropdown-menu"> {btns} </ul>
                </div>
                {input}
            </div>
        );
    }
}

/* ----------------------------------------------Form的分割线-------------------------------------------------------- */

class StrategyForm extends Component{
    render() {
        return (
            <div className='row'>
                <div className="row">
                    <div className="col-lg-2">
                        <div className="col-sm-3">
                            <button id={"formula_btn"}
                                className="btn btn-default glyphicon glyphicon-thumbs-up"
                                type="button"
                                onClick={this.props.add_strategy} />
                        </div>
                        <div className="col-sm-9">
                            <SearchInputMenu id="search_input" add={this.props.add}/>
                        </div>
                    </div>
                    <div className="col-lg-9" >
                        <FormulaLabel id={"formula_label"} list={this.props.formula} remove={this.props.remove}/>
                    </div>
                    <div className="col-lg-1" >
                        <input id='strategy_name' type="text" className="form-control" placeholder="策略名称"/>
                    </div>
                </div>
                <div className="row">
                    <div className='col-lg-12'>
                        <StrategyTable list={this.props.strategy}
                                       remove={this.props.remove_strategy}
                                       edit={this.props.edit}
                        />
                    </div>
                </div>
            </div>
        );
    }

}

class StrategyRow extends Component{
    constructor(props) {
        super(props);
        this.state = {
            forceBuy: false,
            forceSell: false
        }
    }

    checkedBuy(){
        this.state.forceBuy = !this.state.forceBuy;
        this.setState(()=>{return {forceBuy: this.state.forceBuy}});
    }

    checkedSell(){
        this.state.forceSell = !this.state.forceSell;
        this.setState(()=>{return {forceSell: this.state.forceSell}});
    }

    deleteThisRows() {
        this.props.remove(this.props.data);
    }

    editThisRows() {
        this.props.edit(this.props.data);
    }

    render() {
        let forceBuy = this.state.forceBuy,
            forceSell = this.state.forceSell,
            checkStyle = {
                width: '20px',
                height: '20px',
                textAlign: 'center',
                marginLeft: '10px',
                cursor: 'pointer',
                background: '#fff'
            };

        let name = [];
        for (let i of this.props.data){
            name.push(i.name);
        }
        return (
            <tr>
                <td>
                    <div className="btn-group">
                        <button className="btn btn-xs btn-danger" onClick={this.deleteThisRows.bind(this)}>删</button>
                        <button className="btn btn-xs btn-primary" onClick={this.editThisRows.bind(this)}>修</button>
                    </div>
                </td>
                <td>{name.join(' ')}</td>
                <td>
                    <input type="checkbox"
                           checked={forceBuy}
                           onClick={this.checkedBuy.bind(this)}
                           style={checkStyle}
                    />
                </td>
                <td>
                    <input type="checkbox"
                           checked={forceSell}
                           onClick={this.checkedSell.bind(this)}
                           style={checkStyle}
                    />
                </td>
            </tr>
        );
    }
}
class StrategyTable extends Component{
    render() {
        let rows = this.props.list.map(data=>{
            return <StrategyRow data={data} remove={this.props.remove} edit={this.props.edit}/>
        });
        let hidden = 'hidden';
        if (rows.length > 0){
            hidden = '';
        }
        return (
            <table id='strategy_table' className='table' hidden={hidden}>
                <tr>
                    <th style={{width: '5%'}} />
                    <th style={{width: '85%'}}>策略公式</th>
                    <th style={{width: '5%'}}>强制买</th>
                    <th style={{width: '5%'}}>强制卖</th>
                </tr>
                {rows}
            </table>
        );
    }
}

class FormulaOperand extends Component{
    constructor(props) {
        super(props);
        this.state = {
            style: {
                height: '33px',
            }
        }
    }

    click(event){
        if (event.button === 2){
            this.props.remove(this.props.data);
        }
    }

    render(){
        let style = this.state.style;
        let name = this.props.data.name;
        if (['$', '&', '@'].indexOf(name[0]) !== -1){
            name = name.slice(1);
        }
        return (
            <button className={"btn btn-primary"} style={style} onMouseDown={this.click.bind(this)}>
                {name}
            </button>
        );
    }
}
class FormulaOperator extends Component{
    constructor(props) {
        super(props);
        this.state = {
            style: {
                height: '33px',
                width: '33px'
            },
            modalIsOpen: false
        };

        this.openModal = this.openModal.bind(this);
        this.closeModal = this.closeModal.bind(this);
    }

    openModal() {
        this.setState(()=>{return {modalIsOpen: true}});
    }

    closeModal() {
        this.setState(()=>{return {modalIsOpen: false}});
    }

    click(event){
        if (event.button === 2){
            this.props.remove(this.props.data);
        }
    }

    render(){
        let style = this.state.style;
        return (
            <button className={"btn btn-default"} style={style} onMouseDown={this.click.bind(this)}>
                {this.props.data.name}
            </button>
        );
    }
}
class FormulaLabel extends Component{
    constructor(props) {
        super(props);
        this.state = {
            style: {
                borderRadius: "5px",
                border: "1px dotted #C0C0C0",
                height: "35px",
                width: '100%'
            }
        }
    }
    render() {
        let btns = this.props.list.map(item=>{
            if (item.type === 'operand'){
                return <FormulaOperand data={item} remove={this.props.remove}/>
            }else{
                return <FormulaOperator data={item} remove={this.props.remove}/>
            }
        });
        let style = this.state.style;
        return (
            <div id={this.props.id} style={style} className="btn-group">
                {btns}
            </div>
        );
    }
}

class SearchInputMenuItem extends Component{
    click() {
        this.props.add(this.props.data);
    }
    render() {
        return (
            <li><a id={'search_input_menu_'+this.props.data.id} onClick={this.click.bind(this)}>
                {this.props.data.name}
            </a></li>
        );
    }
}
class SearchInputMenu extends Component{
    constructor(props) {
        super(props);
        this.state = {
            style: {
                display: 'none'
            },
            search_menu: []
        }
    }

    search(event) {
        if (event.target.value !== undefined){
            $.get(`/config/query/primary/?q=${event.target.value}`, (result)=>{
                let display = 'none';
                this.state.search_menu = [];
                if (result.length >= 1){
                    for (let item of result){
                        this.state.search_menu.push({id:item.id, name:item.name, type:'operand'});
                    }
                    display = 'inline'
                }
                console.log(this.state.search_menu);
                this.setState(()=>{
                    return {
                        style: {
                            display: display
                        },
                        search_menu: this.state.search_menu
                    }
                });
            });
        }
    }

    enter(event) {
        if (event.key === 'Enter'){
            if (['(', ')', '+', '-', '*', '/', '%', '<=', '>=', '>', '<', '=='].indexOf(event.target.value) !== -1){
                this.props.add({type: 'operator', name: event.target.value});
            }else{
                this.props.add({type: 'operand', name: event.target.value});
            }
            event.target.value = '';
        }
    }

    add(value) {
        this.props.add(value);
        $(`#${this.props.id}`).val("");
        this.setState(()=>{
            return {
                search_menu: [],
                style: {
                    display: 'none'
                }
            }
        });
    }

    render() {
        let style = this.state.style;
        let menu_items = this.state.search_menu.map(item=>{
            return <SearchInputMenuItem key={item.name} data={item} add={this.add.bind(this)}
            />
        });
        return (
            <div className="input-group">
                <input id={this.props.id} type="text" className="form-control" style={{borderRadius: '20px'}}
                       onChange={this.search.bind(this)}
                       onKeyPress={this.enter.bind(this)}
                       data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"/>
                <ul className="dropdown-menu" id={this.props.id+'_menu'} style={style}>
                    {menu_items}
                </ul>
            </div>
        );
    }
}